//
//  YYLoginViewController.swift
//  STMusic
//
//  Created by stoneobs on 17/4/1.
//  Copyright © 2017年 stoneobs. All rights reserved.
//

import UIKit

class YYLoginViewController: STTableViewController {

    var accountTextfiled:UITextField?
    var pwdTextfiled:UITextField?
    var loginButton:STButton?
    
    let themeColor = YYThemeStyleManger.defultManger.currentColor;
    override func viewDidLoad() {
        super.viewDidLoad()
        self.initSubviews();
        
        if YYUserLoginedDefultManger.shared().token() != nil {
            //默认登录，直接跳转
             self.goTabbarVC();
        }
        NotificationCenter.default.addObserver(self, selector: #selector(didReciveNotifacationAction(notify:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil);
        self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:FlatBlackDark()];

        // Do any additional setup after loading the view.
    }
    func didReciveNotifacationAction(notify:NSNotification) -> Void {
        
        if (self.accountTextfiled?.text?.characters.count)! == 11  &&
            (self.pwdTextfiled?.text?.characters.count)! > 5{
            
            self.loginButton?.isUserInteractionEnabled = true;
            self.loginButton?.backgroundColor = themeColor;
        }else{
            
            self.loginButton?.isUserInteractionEnabled = false;
            self.loginButton?.backgroundColor = NO_USER_INTERFACE_COLOR;
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self);
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
        self.hideNavagetionbar();
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);


    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);
        self.showNavagationbar();
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    // MARK:privite Method
    func initSubviews() -> Void {
        
        weak var weakSelf = self;
        let font = UIFont.init(name: "AmericanTypewriter-Bold", size: 18);
        
        //背景图
        let imageView = UIImageView.init(frame: .init(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT));
        imageView.image = UIImage.init(named: "img_login_background");
        self.tableView.backgroundView = imageView;
       
        
        let visEffect = UIBlurEffect.init(style: .light);
        let visoulView = UIVisualEffectView.init(frame: imageView.bounds)
        visoulView.effect = visEffect;
        visoulView.alpha = 0.75;
        imageView.addSubview(visoulView);
        
        
        //头像
        let iconButton = STButton.init(frame: .init(x: 0, y: 110, width: 100, height: 100),
                                       title: nil,
                                       titleColor: nil,
                                       titleFont: 0,
                                       cornerRadius: 50,
                                       backgroundColor: nil,
                                       backgroundImage: UIImage.init(named: "IMG_0031"),
                                       image: nil);
        iconButton?.sd_setImage(with: URL.init(string: YYUserLoginedDefultManger.shared().currentUser().iconUrl!), for: .normal, placeholderImage: ThemePeopleImage, options: .retryFailed);
        iconButton?.centerX = SCREEN_WIDTH / 2;
        iconButton?.showRightShadow();
        iconButton?.isUserInteractionEnabled = false;
        iconButton?.setBrderWidth(1.5, borderColor: themeColor);
        self.tableView.addSubview(iconButton!);
        
       



        
        //账号
        accountTextfiled = UITextField.init(frame: .init(x: 0, y: (iconButton?.bottom)! + 40, width: 0.7 * SCREEN_WIDTH, height: 40));
        accountTextfiled?.placeholder = "请输入账号";
        accountTextfiled?.centerX = SCREEN_WIDTH / 2;
        accountTextfiled?.textColor = .white;
        accountTextfiled?.tintColor = themeColor;
        accountTextfiled?.font = font;
        accountTextfiled?.text = YYUserLoginedDefultManger.shared().currentUser().username;
        accountTextfiled?.keyboardType = .numberPad;
        accountTextfiled?.attributedPlaceholder = NSAttributedString.init(string: "请输入账号", attributes: [NSForegroundColorAttributeName:UIColor.white]);
        self.tableView    .addSubview(accountTextfiled!);
        
        let accountLeftView = UIImageView.init(frame: .init(x: 0, y: 0, width: 20, height: 20));
        accountLeftView.image = UIImage.init(named: "img_account");
        self.accountTextfiled?.leftView = accountLeftView;
        self.accountTextfiled?.leftViewMode = .always;
        
        let accountLine  = UIView.init(frame:CGRect.init(x: 0, y: (accountTextfiled?.bottom)! + 1.0, width: (accountTextfiled?.width)!, height: 0.5));
        accountLine.backgroundColor = themeColor;
        self.tableView.addSubview(accountLine);
        
        accountLine.centerX = SCREEN_WIDTH / 2;
        accountTextfiled?.centerX = SCREEN_WIDTH / 2;
        accountTextfiled?.clearButtonMode = .whileEditing;
        accountTextfiled?.textAlignment = .center;
        
        //密码
        pwdTextfiled = UITextField.init(frame: .init(x: 0, y: (accountTextfiled?.bottom)! + 10, width: 0.7 * SCREEN_WIDTH, height: 40));
        pwdTextfiled?.placeholder = "请输入密码";
        pwdTextfiled?.centerX = SCREEN_WIDTH / 2;
        pwdTextfiled?.textColor = .white;
        pwdTextfiled?.tintColor = themeColor;
        pwdTextfiled?.font = font;
        pwdTextfiled?.keyboardType = .asciiCapable;
        pwdTextfiled?.isSecureTextEntry = true;
        pwdTextfiled?.attributedPlaceholder = NSAttributedString.init(string: "请输入密码", attributes: [NSForegroundColorAttributeName:UIColor.white]);
        self.tableView.addSubview(pwdTextfiled!);
        
        let pwdLeftView = UIImageView.init(frame: .init(x: 0, y: 0, width: 20, height: 20));
        pwdLeftView.image = UIImage.init(named: "img_password");
        self.pwdTextfiled?.leftView = pwdLeftView;
        self.pwdTextfiled?.leftViewMode = .always;
        
        let pwdLine  = UIView.init(frame:CGRect.init(x: 0, y: (pwdTextfiled?.bottom)! + 1.0, width: (accountTextfiled?.width)!, height: 0.5));
        pwdLine.backgroundColor = themeColor;
        self.tableView.addSubview(pwdLine);
        
        pwdLine.centerX = SCREEN_WIDTH / 2;
        pwdTextfiled?.centerX = SCREEN_WIDTH / 2;
        pwdTextfiled?.clearButtonMode = .whileEditing;
        pwdTextfiled?.textAlignment = .center;
        
        //忘记密码
        
        let fogotButton = STButton.init(frame: .init(x: 0, y: (pwdTextfiled?.bottom)! + 20, width: (accountTextfiled?.width)! - 30, height: 16),
                                        title: "忘记密码?",
                                        titleColor: themeColor,
                                        titleFont: 15,
                                        cornerRadius: 5,
                                        backgroundColor: .clear,
                                        backgroundImage: nil,
                                        image: nil);
        fogotButton?.centerX = SCREEN_WIDTH / 2;
        fogotButton?.clicAction = { button -> Void in
            //点击事件
            print("点击了忘记密码")
            weakSelf?.navigationController?.pushViewController(YYForgotPwdViewController(), animated: true);
            
        };
        fogotButton?.right = (accountTextfiled?.right)!;
        fogotButton?.contentHorizontalAlignment = .right;
        self.tableView.addSubview(fogotButton!);
        
        
        //登陆
        self.loginButton = STButton.init(frame: .init(x: 0, y: (pwdTextfiled?.bottom)! + 60, width: (accountTextfiled?.width)! - 30, height: 40),
                                       title: "登录",
                                       titleColor: .white,
                                       titleFont: 15,
                                       cornerRadius: 5,
                                       backgroundColor: themeColor,
                                       backgroundImage: nil,
                                       image: nil);
        loginButton?.centerX = SCREEN_WIDTH / 2;
        loginButton?.showRightShadow();
        loginButton?.clicAction = { button -> Void in
            //点击事件
            print("点击了登陆")

            weakSelf?.loadLoginNetWorkRequest();
  
        };
        loginButton?.contentHorizontalAlignment = .center;
        loginButton?.isUserInteractionEnabled = false;
        loginButton?.backgroundColor = NO_USER_INTERFACE_COLOR;
        self.tableView.addSubview(loginButton!);
        
        //注册
        let registerButton = STButton.init(frame: .init(x: 0, y: (loginButton?.bottom)! + 40, width: (accountTextfiled?.width)! - 30, height: 15),
                                        title: "没有账号？立即注册",
                                        titleColor: themeColor,
                                        titleFont: 17,
                                        cornerRadius: 5,
                                        backgroundColor: .clear,
                                        backgroundImage: nil,
                                        image: nil);
        registerButton?.centerX = SCREEN_WIDTH / 2;
    
        registerButton?.clicAction = { button -> Void in
            //点击事件
            print("点击了注册")

            weakSelf?.navigationController?.pushViewController(YYRegisterViewController(), animated: true);
            
        };
        registerButton?.contentHorizontalAlignment = .center;
        self.tableView.addSubview(registerButton!);
    }
        // MARK:Network Request
    
    func loadLoginNetWorkRequest() -> Void {
        
        SVProgressHUD.show(withStatus: "登录中");
        BmobUser.loginWithUsername(inBackground:  self.accountTextfiled?.text , password: self.pwdTextfiled?.text, block: { (loginedUser, loginerror) in
            
            if (loginerror != nil){
                let myError:NSError = loginerror! as NSError;
                print(myError.code);
                SVProgressHUD.showError(withStatus: YYUtils.bmobErrorDes(error: loginerror!));
                
            }else{
                
                let time:Int = Int(NSDate().timeIntervalSince1970);
                let token:NSString = NSString.init(string: "\(time)");
                
                let userDic = loginedUser?.mj_keyValues();
                let dic:Dictionary<String,Any> = userDic!["dataDic"] as! Dictionary<String,Any>;
                let userModel = YYUserModel.mj_object(withKeyValues: dic);
                YYUserLoginedDefultManger.shared().updateUserDefult(userModel);
                UserDefaults.standard.setValue(String(token.md532BitLower()), forKey: YYLOGIN_TOKEN);
               
                UserDefaults.standard.synchronize();
                print(NSHomeDirectory());
                
                self.goTabbarVC();
                SVProgressHUD.dismiss();
                SVProgressHUD.showSuccess(withStatus: "登录成功");
                
            }
        })

    }

    func goTabbarVC() -> Void {
        let rootVC = STLayoutViewController.defaultLayout();
        rootVC.leftViewController = STNavigationController.init(rootViewController: YYLeftViewController());
        rootVC.leftDisplayMode = STLayoutViewDisplayMode.background;
        rootVC.rightViewController = YYMusciPlayerController.shardPlayer;
        rootVC.rightDisplayMode = STLayoutViewDisplayMode.cover;
        //rootVC.setPanGestureEnable(false);
       UIApplication.shared.keyWindow?.rootViewController = rootVC;
    }
}
